# Definition for singly-linked list.
class ListNode(object):
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next
class Solution(object):
    def removeElements(self, head, val):
        """
        :type head: Optional[ListNode]
        :type val: int
        :rtype: Optional[ListNode]
        """
        while head is not None and head.val == val:
            head = head.next
        current = head
        while current is not None and current.next is not None:
            if current.next.val == val:
                current.next = current.next.next
            else:
                current = current.next
        return head

# 工具函数：从列表构造链表
def build_linked_list(values):
    if not values: # 空列表
        return None
    head = ListNode(values[0]) # 头节点
    current = head
    for val in values[1:]:
        current.next = ListNode(val)
        current = current.next
    return head

# 工具函数：打印链表
def print_linked_list(head):
    result = []
    while head:
        result.append(head.val)
        head = head.next
    print(result)

if __name__ == '__main__':
    # 示例1
    values = [1, 2, 6, 3, 4, 5, 6]
    head = build_linked_list(values)
    new_head = Solution().removeElements(head, 6)
    print_linked_list(new_head) # [1, 2, 3, 4, 5]